package com.feicheng.service.a;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.common.task.Cache;
import com.feicheng.persistence.entity.*;
import com.feicheng.persistence.mapper.*;
import com.feicheng.persistence.model.SkjlModel;
import com.feicheng.persistence.service.*;
import com.feicheng.persistence.entity.Ajiaolian;
import com.feicheng.persistence.service.IAhylxService;
import com.feicheng.persistence.service.IAjiaolianService;
import com.feicheng.wxapi.pay.WxAppPayBean;
import com.feicheng.wxapi.pay.transfer.model.TransferBillsResponse;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FJlService {

    @Autowired
    IAjiaolianService jiaolianService;

    @Autowired
    IAmenjinService menjinService;

    @Autowired
    IAkechengskjlService skjlService;

    @Autowired
    IAmountService amountService;

    @Autowired
    IAmdjlService amdjlService;

    @Autowired
    IAdzService adzService;

    @Autowired
    IAhylxService hylxService;

    @Autowired
    IAkechengService kechengService;

    @Autowired
    IAkechenglxService kechenglxService;

    @Autowired
    IAkechengitemService akechengitemService;

    @Autowired
    IAjlpjService jlpjService;

    @Autowired
    IAclientbmService aclientbmService;

    @Autowired
    IClientService clientService;

    @Autowired
    IAroomyyjlService yyjlService;

    @Autowired
    IAhyjlService hyjlService;

    @Autowired
    IAfxjlService fxjlService;

    @Autowired
    WxAppPayBean wxAppPayBean;

    @Autowired
    Cache cache;

    @Autowired
    IAjiaolianService ajiaolianService;

    private String appid;

    private Integer yj;

    @PostConstruct
    private void init() {
        Asetting asetting = cache.getObject("Asetting", Asetting.class);
        appid = asetting.getJappid();
        yj = asetting.getJlyj();
    }

    public JSONObject rejectFx(JSONObject param) {
        String fxjlid = param.getString("fxjlid");
        Afxjl afxjl = new Afxjl();
        afxjl.setFxjlid(fxjlid);
        afxjl.setStu("J");
        fxjlService.updateById(afxjl);
        param.put("afxjl", fxjlService.getById(fxjlid));
        return param;
    }

    @Transactional
    public synchronized void jiesuanHy() {
        LocalDate now = LocalDate.now();
        LocalDate nowBefor90D = now.minusDays(90);
        QueryWrapper<Ahyjl> qw = new QueryWrapper<>();
        qw.eq("stu", "F");
        qw.le("ed", nowBefor90D);

        List<Ahyjl> ahyjls = hyjlService.list(qw);
        ahyjls.forEach(hy -> {
            hy.setStu("G");
            hyjlService.updateById(hy);

            Ajiaolian ajiaolian = jiaolianService.getById(hy.getJlid());
            Amount jlAmount = amountService.getById(ajiaolian.getOpenid());
            jlAmount.setAmount(jlAmount.getAmount().intValue() + hy.getAmount() + hy.getYezfje());
            amountService.updateById(jlAmount);
        });
    }

    @Transactional
    public synchronized void jiesuanBm() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nowBeror90D = now.minusDays(90);
        QueryWrapper<Aclientbm> qwbm = new QueryWrapper<>();
        qwbm.eq("stu", "F");
        qwbm.le("ct", nowBeror90D);
        List<Aclientbm> aclientbms = aclientbmService.list(qwbm);

        if (null != aclientbms && aclientbms.size() > 0) {
            aclientbms.forEach(bm -> {
                bm.setStu("G");
                bm.setCt(now);
                aclientbmService.updateById(bm);
                String openId = "";

                if (StringUtils.hasLength(bm.getJlid())) {
                    Ajiaolian ajiaolian = jiaolianService.getById(bm.getJlid());
                    openId += ajiaolian.getOpenid();
                } else if (StringUtils.hasLength(bm.getMdjlid())) {
                    Amdjl amdjl = amdjlService.getById(bm.getMdjlid());
                    Adz adz = adzService.getById(amdjl.getDzid());
                    openId += adz.getOpenid();
                }

                if (StringUtils.hasLength(openId)) {
                    Amount jlAmount = amountService.getById(openId);
                    jlAmount.setAmount(jlAmount.getAmount().intValue() + bm.getSjzfje() + bm.getYezfje());


                    if (StringUtils.hasLength(bm.getFxjlid())) {
                        Afxjl afxjl = fxjlService.getById(bm.getFxjlid());
                        Client fromClient = clientService.getById(afxjl.getFxclientid());
                        Amount fromAmount = amountService.getById(fromClient.getOpenid());

                        if ("T".equals(afxjl.getStu())) {
                            fromAmount.setAmount(fromAmount.getAmount() + afxjl.getFxje());
                            amountService.updateById(fromAmount);
                            jlAmount.setAmount(jlAmount.getAmount() - afxjl.getFxje());
                        }
                    }

                    amountService.updateById(jlAmount);
                }

            });
        }
    }


    /**
     * 教练扫脸接口
     * @param param
     * @return
     */
    public JSONObject sl(JSONObject param) {
        String jlid = param.getString("jlid");
        String mjid = param.getString("mjid");

        if (!StringUtils.hasLength(jlid)) {
            throw new SystemException(jlid + "：教练没有被找到");
        }

        if (!StringUtils.hasLength(mjid)) {
            throw new SystemException(mjid + "：门禁没有被找到");
        }
        Amenjin menjin = menjinService.getById(mjid);

        String roomid = param.getString("roomid");
        String storeid = param.getString("storeid");
        if (!StringUtils.hasLength(roomid)) {
            roomid = menjin.getUkey();
            storeid = menjin.getStoreid();
        }

        if (!StringUtils.hasLength(storeid)) {
            storeid = param.getString("storeid");
        }

        LocalTime st = LocalTime.now().plusMinutes(10);
        LocalTime et = LocalTime.now().minusMinutes(10);

        QueryWrapper<SkjlModel> skjlqw = new QueryWrapper<>();
        skjlqw.eq("ajiaolian.jlid", jlid);
        skjlqw.eq("akechengskjl.dt", LocalDate.now());
        if (StringUtils.hasLength(roomid)) {
            skjlqw.eq("akechengitem.roomid", roomid);
        }
        skjlqw.eq("akechengitem.storeid", storeid);
        skjlqw.le("akechengskjl.st", st);
        skjlqw.ge("akechengskjl.et", et);
        AkechengskjlMapper skjlMapper = (AkechengskjlMapper) skjlService.getBaseMapper();
        List<SkjlModel> skjlModelList = skjlMapper.getSkjlWithKcitem(skjlqw);
        if (skjlModelList.size() > 0) {

        } else {

            /* 出门 */
            if (menjin.getFlg()) {
            /* 进门 */
            } else {
                throw new SystemException(jlid + "：当前没有课程；无权进入房间【"+roomid);
            }

        }
        return param;
    }


    /**
     * 教练分页查询 可鑫姐
     * @param param
     * @return
     */
    public JSONObject getJlByPage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);
        QueryWrapper<JSONObject> qw = new QueryWrapper<>();

        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("ajiaolian.jlid", jlid);
        }

        String jlname = param.getString("jlname");
        if (StringUtils.hasLength(jlname)) {
            qw.like("ajiaolian.jlname", jlname);
        }

        //根据课程类型查
        String lx = param.getString("lx");
        if (StringUtils.hasLength(lx)) {
            qw.like("ajiaolian.lx ", lx);
        }

        String astoreid = param.getString("astoreid");
        if (StringUtils.hasLength(astoreid)) {
            QueryWrapper<Akechengitem> kcItemqw = new QueryWrapper<>();
            kcItemqw.select("DISTINCT kcid").eq("storeid", astoreid);
            JSONArray kcids = new JSONArray();
            akechengitemService.getBaseMapper().selectList(kcItemqw, item -> {
                kcids.add(item.getResultObject().getKcid());
            });
            param.put("kcids", kcids);

            QueryWrapper<Akecheng> qwkc = new QueryWrapper<>();
            qwkc.select("jlid");
            List<Akecheng> kcs = kechengService.list(qwkc);
            List<String> jlids = kcs.stream().map(Akecheng::getJlid).collect(Collectors.toList());
            param.put("jlids", jlids);
        }

        String aroomid = param.getString("aroomid");
        if (StringUtils.hasLength(aroomid)) {
            QueryWrapper<Akechengitem> kcItemqw = new QueryWrapper<>();
            kcItemqw.select("DISTINCT kcid").eq("aroomid", aroomid);
            JSONArray kcids = new JSONArray();
            akechengitemService.getBaseMapper().selectList(kcItemqw, item -> {
                kcids.add(item.getResultObject().getKcid());
            });
            param.put("kcids", kcids);

            QueryWrapper<Akecheng> qwkc = new QueryWrapper<>();
            qwkc.select("jlid");
            List<Akecheng> kcs = kechengService.list(qwkc);
            List<String> jlids = kcs.stream().map(Akecheng::getJlid).collect(Collectors.toList());
            param.put("jlids", jlids);
        }

        JSONArray jlids = param.getJSONArray("jlids");
        if (null != jlids && jlids.size() > 0) {
            qw.in("ajiaolian.jlid", jlids);
        }

        AjiaolianMapper ajiaolianMapper =
                (AjiaolianMapper) jiaolianService.getBaseMapper();

        page = ajiaolianMapper.getJlWithKcByPage(page, qw);
        param.put("ajiaolians", page);

        return param;
    }

    /*平台端教练分页*/
    public JSONObject getJlsByPage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> qwjl = new QueryWrapper<>();

        String jlname = param.getString("jlname");
        if (StringUtils.hasLength(jlname)) {
            qwjl.like("ajiaolian.jlname", jlname);
        }

        AjiaolianMapper ajiaolianMapper= (AjiaolianMapper)jiaolianService.getBaseMapper();

        page = ajiaolianMapper.getJlsByPage(page, qwjl);
        param.put("ajiaolians", page);

        return param;
    }

    /**
     * 教练修改 老蔡
     * @param param
     * @return
     */
    public JSONObject updateJl(JSONObject param) {
        Ajiaolian ajiaolian = param.getObject("ajiaolian", Ajiaolian.class);
        jiaolianService.updateById(ajiaolian);
        return param;
    }

    /**
     * 教练详细查询 斌哥
     * @param param
     * @return
     */
    public JSONObject getJl(JSONObject param) {

        String jlid = param.getString("jlid");
        if (!StringUtils.hasLength(jlid)) {
            throw new SystemException("教练id必须指定");
        }
        // 教练信息
        Ajiaolian ajiaolian = jiaolianService.getById(jlid);
        param.put("ajiaolian", ajiaolian);

        Amount amount = amountService.getById(ajiaolian.getOpenid());
        param.put("amount", amount);

        List<Akechenglx> lxs = kechenglxService.list();
        param.put("lxs", lxs);

        // 课程信息
        QueryWrapper<Akecheng> kcqw = new QueryWrapper<>();
        kcqw.eq("jlid",ajiaolian.getJlid());
        Long kccount = kechengService.count(kcqw);
        param.put("kcnumber", kccount);

        //预约记录
        QueryWrapper<Aroomyyjl> yyqw = new QueryWrapper<>();
        yyqw.eq("jlid",ajiaolian.getJlid());
        Long yyjlcount = yyjlService.count(yyqw);
        param.put("yyjlnumber", yyjlcount);

        // 会员信息
        QueryWrapper<Ahyjl> hyjlqw = new QueryWrapper<>();
        hyjlqw.eq("jlid", ajiaolian.getJlid());
        Long hyjlcount = hyjlService.count(hyjlqw);
        param.put("hynumber", hyjlcount);

        // 会员类型信息
        QueryWrapper<Ahylx> hylxqw = new QueryWrapper<>();
        hylxqw.eq("jlid", ajiaolian.getJlid());
        List<Ahylx> ahylxs = hylxService.list(hylxqw);
        param.put("ahylxs", ahylxs);

        // 教练评价信息
        QueryWrapper<Ajlpj> jlpjqw = new QueryWrapper<>();
        jlpjqw.eq("jlid", ajiaolian.getJlid());
        Long pjcount = jlpjService.count(jlpjqw);
        param.put("pjnumber", pjcount);

        QueryWrapper<Aclientbm> qwbm = new QueryWrapper<>();
        qwbm.eq("jlid", jlid);
        qwbm.eq("pflg", true);
        Set<String> clientids = new HashSet<String>();
        List<Aclientbm> bms = aclientbmService.list(qwbm);
        param.put("bmnumber", bms.size());
        if (null != bms && !bms.isEmpty()) {
            bms.forEach(bm -> {
                clientids.add(bm.getClientid());
            });
        }
        param.put("clientids", clientids);
        return param;
    }

    /**
     * 会员类型新增 仕哥
     * @param param
     * @return
     */
    public JSONObject newHylx(JSONObject param) {
        Ajiaolian ajiaolian = param.getObject("ajiaolian", Ajiaolian.class);

        Ahylx ahylx = param.getObject("ahylx", Ahylx.class);
        ahylx.setHylxid(StringGenerator.getID("HYLX"));

        if (!StringUtils.hasLength(ahylx.getHlname())) {
            throw new SystemException("会员类型名称不能为空");
        }
        if (null == ahylx.getAmount() || ahylx.getAmount() <= 0) {
            throw new SystemException("价格必须设置");
        }
        ahylx.setJlid(ajiaolian.getJlid());
        ahylx.setFlg(true);
        ahylx.setStu(true);
        hylxService.save(ahylx);
        param.put("ahylx",ahylx);
        return param;
    }

    /*会员类型详细*/
    public JSONObject getHylx(JSONObject param) {
        String hylxid = param.getString("hylxid");
        if (!StringUtils.hasLength(hylxid)) {
            throw new SystemException("会员类型ID不能为空");
        }
        Ahylx hylx = hylxService.getById(hylxid);
        param.put("hylx", hylx);

        Ajiaolian ajiaolian = jiaolianService.getById(hylx.getJlid());
        param.put("ajiaolian", ajiaolian);
        return param;
    }

    /**
     * 会员类型查询 仕哥
     * @param param
     * @return
     */
    public JSONObject getHylxs(JSONObject param) {
        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);


        QueryWrapper<JSONObject> qw = new QueryWrapper<>();

        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("ajiaolian.jlid", jlid);
        }

        String jlname = param.getString("jlname");
        if (StringUtils.hasLength(jlname)) {
            qw.like("ajiaolian.jlname", jlname);
        }

        AhylxMapper ahylxMapper = (AhylxMapper) hylxService.getBaseMapper();
        page = ahylxMapper.selectHylxs(page, qw);
        param.put("ahylx", page);
        return param;
    }

    public JSONObject getPjBypage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<Ajlpj> page = new Page<Ajlpj>(current, size);

        QueryWrapper<Ajlpj> qw = new QueryWrapper<>();
        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("jlid", jlid);
        }

        page = jlpjService.page(page, qw);
        param.put("ajlpjs", page);

        return param;
    }


    public JSONObject getPjByList(JSONObject param) {

        QueryWrapper<Ajlpj> qw = new QueryWrapper<>();
        String clientid = param.getString("clientid");
        if (StringUtils.hasLength(clientid)) {
            qw.eq("clientid", clientid);
        }
        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("jlid", jlid);
        }
        List<Ajlpj> ajlpjs = jlpjService.list(qw);
        param.put("ajlpjs", ajlpjs);

        return param;
    }

    /**
     * 评价教练
     * @param param
     * @return
     */
    public JSONObject pjJl(JSONObject param) {
        Ajlpj ajlpj = param.getObject("ajlpj", Ajlpj.class);
        ajlpj.setJlpjid(StringGenerator.getID("JLPJ"));
        ajlpj.setCt(LocalDateTime.now());
        jlpjService.save(ajlpj);
        param.put("ajlpj", ajlpj);
        return param;
    }

    public JSONObject getPj(JSONObject param) {
        String jlpjid = param.getString("jlpjid");
        param.put("ajlpj", jlpjService.getById(jlpjid));
        return param;
    }

    // 平台端分销记录分页
    public JSONObject getFxjlByPage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> qwfxjl = new QueryWrapper<>();

        AfxjlMapper afxjlMapper= (AfxjlMapper)fxjlService.getBaseMapper();

        IPage<JSONObject> fxjlWithClandJlByPage = afxjlMapper.getFxjlWithClandJlByPage(page, qwfxjl);
        param.put("fxjl", fxjlWithClandJlByPage);

        return param;
    }

    // 平台端分销记录查询
    public JSONObject getFxjlInfo(JSONObject param) {
        String fxjlid = param.getString("fxjlid");
        if (!StringUtils.hasLength(fxjlid)) {
            throw new SystemException("分销记录ID不能为空");
        }

        QueryWrapper<JSONObject> qwfxjl = new QueryWrapper<>();
        qwfxjl.eq("fxjlid", fxjlid);

        AfxjlMapper afxjlMapper= (AfxjlMapper)fxjlService.getBaseMapper();
        List<JSONObject> fxjlWithClandJlByList = afxjlMapper.getFxjlWithClandJlByList(qwfxjl);
        param.put("fxjl", fxjlWithClandJlByList);
        return param;
    }

    public JSONObject yjin(JSONObject param) {
        String jlid = param.getString("jlid");
        Ajiaolian ajiaolian = ajiaolianService.getById(jlid);
        PrepayWithRequestPaymentResponse prepayData =
                wxAppPayBean.jsapi(
                        StringGenerator.getID("JLYJ"),
                        "押金订单",
                        "/notice-url/"+jlid,
                        yj,
                        ajiaolian.getOpenid(),
                        "",
                        appid
                );
        String prepayId = prepayData.getPackageVal().split("=")[1];

        ajiaolian.setPrepayid(prepayId);
        ajiaolian.setPrepaydata(JSONObject.toJSONString(prepayData));
        ajiaolianService.updateById(ajiaolian);
        param.put("ajiaolian", ajiaolian);
        return param;
    }

    @Transactional
    public JSONObject yjout(JSONObject param) {
        String jlid = param.getString("jlid");
        Ajiaolian ajiaolian = ajiaolianService.getById(jlid);
        ajiaolian.setYj(0);

        Amount amount = amountService.getById(ajiaolian.getOpenid());
        amount.setAmount(amount.getAmount() + yj);

        ajiaolianService.updateById(ajiaolian);
        amountService.updateById(amount);
        return param;
    }

    public void afterYjin(String jlid) {
        Ajiaolian jiaolian = ajiaolianService.getById(jlid);
        jiaolian.setYj(yj);
        jiaolianService.updateById(jiaolian);
    }
}
